<?php
/**
 * Author:xsc
 * Time:2023/10/25 13:17
 */

namespace App\Jobs;

use App\Common\Tools;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Repository\MemberRepo;
use App\Extensions\Coupon\CouponService;
use App\Repository\SpecialPrivilegeRepo;
use App\Repository\GoodsRepo;
use App\Repository\SpecialPrivilegeOrderRepo;
use App\Repository\MerchantsInfoRepo;

class PrivilegeAutoReceiveJob extends Job
{

    use  InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务可尝试的次数
     * @var int
     */
    public $tries = 3;

    /**
     * 任务失败前允许的最大异常数
     * @var int
     */
    public $maxExceptions = 3;

    /**
     * 在超时之前任务可以运行的秒数
     * @var int
     */
    public $timeout = 30;

    private $privilege_id;

    private $goods_id;

    public function __construct(int $privilege_id, int $goods_id)
    {
        $this->privilege_id = $privilege_id;
        $this->goods_id = $goods_id;
    }

    public function handle()
    {
        $privilege_id = $this->privilege_id;
        $goods_id = $this->goods_id;

        Log::info('[赋能自动领取]' . $privilege_id . '_' . $goods_id);

        // 赋能信息
        $privilege_info = SpecialPrivilegeRepo::getInstance()->getInfo($privilege_id);

        if (!$privilege_info) {
            Log::info('[赋能自动领取]赋能不存在' . $privilege_id);
            return false;
        }

        if ($privilege_info['status'] != 1) {
            Log::info('[赋能自动领取]赋能未上架' . $privilege_id);
            return false;
        }

        // 赋能过期
        if (strtotime($privilege_info['coupon_validity_time']) < time()) {
            Log::info('[赋能自动领取]赋能已过期' . $privilege_id);
            return false;
        }

        // 接入商户信息
        $merchants_id = $privilege_info['merchants_id'];
        $merchants_info = MerchantsInfoRepo::getInstance()->getByMerchantsId($merchants_id);
        if (!$merchants_info) {
            Log::info('[赋能自动领取]商户不存在' . $privilege_id);
            return false;
        }

        $special_id = $privilege_info['special_id'];

        // 商品详情
        $goods_info = GoodsRepo::getInstance()->getInfo($goods_id);

        if (!$goods_info || $goods_info['special_id'] != $special_id) {
            Log::info('[赋能自动领取]商品信息错误' . $goods_id);
            return false;
        }

        if ($goods_info['channel'] != 2 || $goods_info['sell_status'] != 0) {
            Log::info('[赋能自动领取]商品状态异常' . $goods_id);
            return false;
        }

        $member_id = $goods_info['member_id'];

        // 用户信息
        $member_info = MemberRepo::getInstance()->getInfoById($member_id);
        if (!$member_info) {
            Log::info('[赋能自动领取]用户不存在' . $member_id);
            return false;
        }

        $mobile = $member_info['mobile'];

        $where = [
            'privilege_id' => $privilege_id,
            'special_id'   => $special_id,
            'goods_id'     => $goods_id,
            'member_id'    => $member_id,
            'neq_status'   => 3,
        ];
        $order_list = SpecialPrivilegeOrderRepo::getInstance()->getList($where);
        if ($order_list) {
            Log::info('[赋能自动领取]已存在赋能订单' . $privilege_id . '_' . $goods_id);
            return false;
        }

        // 新增订单
        $order_sn = Tools::build_hash_no();
        $data = [
            'ordersn'      => $order_sn,
            'privilege_id' => $privilege_id,
            'member_id'    => $member_id,
            'type'         => $privilege_info['type'],
            'status'       => 2,
            'special_id'   => $special_id,
            'goods_id'     => $goods_id,
            'coupon_code'  => $privilege_info['coupon_code'],
            'coupon_id'    => $privilege_info['coupon_id'],
            'thirdNo'      => '',
            'end_time'     => $privilege_info['coupon_validity_time'],
            'create_time'  => date('Y-m-d H:i:s'),
        ];
        $order_id = SpecialPrivilegeOrderRepo::getInstance()->save($data);
        if (!$order_id) {
            Log::info('[赋能自动领取]新增订单失败');
            return false;
        }

        try {
            // 发放
            $params = [
                'sku_code'      => $privilege_info['coupon_code'],
                'coupon_num'    => 1,
                'notice_url'    => env('APP_URL') . '/api/openapi/v1/callback/privilegeAutoReceiveCallback',
                'phone'         => $mobile,
                'third_no'      => $order_sn,
                'collection_no' => $goods_id,
                'channel_code'  => $merchants_info['access_mid'],
            ];
            $coupon = CouponService::getInstance();
            $res = $coupon->buySku($params);

            if ($res) {
                // 1.更新赋能订单
                SpecialPrivilegeOrderRepo::getInstance()->save(['thirdNo' => $res[0]['orderSubNo']], $order_id);

                // 2.增加赋能的领取数量
                SpecialPrivilegeRepo::getInstance()->updateUseNum($privilege_id);

            } else {
                throw new \Exception('发放失败' . $order_sn);
            }
        } catch (\Exception $e) {
            Log::info('[赋能自动领取]失败:' . $e->getMessage());

            // 5s之后再次加入队列
            $this->release(5);
        }
    }

}
